import os

import Exceptions

class WalkHelperIter:
    """
    iter for WalkHelper
    """

    def __init__(self, allfiles):
        self._list = allfiles
        self._index = 0

    def next(self):
        if self._index >= len(self._list):
            raise StopIteration
        self._index = self._index + 1
        return self._list[self._index - 1][0], self._list[self._index - 1][1]
        

class WalkHelper:
    """
    helper for walking dir. 
    """

    def __init__(self, pathlist, recursive = True, filter = None):
        self._allfiles = []
        for path in pathlist:
            path = os.path.abspath(path)
            basename = os.path.basename(path)
            dirname = os.path.dirname(path)
            if os.path.isfile(path):
                if filter == None or filter.match(basename):
                    self._allfiles.append((path, "./"))
            elif os.path.isdir(path):
                if not recursive:
                    for file in os.listdir(path):
                        fullpath = os.path.join(path, file)
                        if os.path.isfile(fullpath) and (filter == None or filter.match(file)):
                            self._allfiles.append((fullpath, basename))
                else:
                    for root, dirs, files in os.walk(path):
                        for file in files:
                            if filter == None or filter.match(file):
                                self._allfiles.append((os.path.join(root, file), os.path.relpath(root, dirname)))
            else:
                raise Exceptions.PathNotExistException(path)

    def __iter__(self):
        return WalkHelperIter(self._allfiles)
        
